package com.stars.easyms.alarm.client.wechat;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>className: MarkdownMessage</p>
 * <p>description: markdown类型消息</p>
 *
 * @author caotieshuan
 * @version 1.5.0
 * @date 2019-12-18 16:21
 */
public class MarkdownMessage implements Message {

    private List<String> items = new ArrayList<>();

    public void add(String text) {
        items.add(text);
    }

    /**
     * 字体加粗
     *
     * @param text 文本内容
     * @return
     */
    public String getBoldText(String text) {
        return "**" + text + "**";
    }

    public String getItalicText(String text) {
        return "*" + text + "*";
    }

    /**
     * 文本链接
     *
     * @param text 文本内容
     * @param href 链接路径
     * @return
     */
    public String getLinkText(String text, String href) {
        return "[" + text + "](" + href + ")";
    }

    /**
     * 标题 （支持1至6级标题，注意#与文字中间要有空格）
     *
     * @param headerType 标题类型
     * @param text       文本内容
     * @return
     */
    public String getHeaderText(int headerType, String text) {
        if (headerType < 1 || headerType > 6) {
            throw new IllegalArgumentException("headerType should be in [1, 6]");
        }

        StringBuffer numbers = new StringBuffer();
        for (int i = 0; i < headerType; i++) {
            numbers.append("#");
        }
        return numbers + " " + text;
    }

    /**
     * 引用文本
     *
     * @param text 文本内容
     * @return
     */
    public String getReferenceText(String text) {
        return "> " + text;
    }

    @Override
    public String toJsonString() {
        Map<String, Object> result = new HashMap<>();
        //消息类型，此时固定为markdown
        result.put("msgtype", "markdown");

        Map<String, Object> markdown = new HashMap<>();
        StringBuffer markdownText = new StringBuffer();
        for (String item : items) {
            markdownText.append(item + "\n");
        }
        //markdown内容，最长不超过4096个字节，必须是utf8编码
        markdown.put("content", markdownText.toString());
        result.put("markdown", markdown);
        return JSON.toJSONString(result);
    }
    @Override
    public Map<String, Object> toMessageMap() {
        Map<String, Object> result = new HashMap<>();
        //消息类型，此时固定为markdown
        result.put("msgtype", "markdown");

        Map<String, Object> markdown = new HashMap<>();
        StringBuffer markdownText = new StringBuffer();
        for (String item : items) {
            markdownText.append(item + "\n");
        }
        //markdown内容，最长不超过4096个字节，必须是utf8编码
        markdown.put("content", markdownText.toString());
        result.put("markdown", markdown);
        return result;
    }
}